package com.ecarx.module_log.view;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.ecarx.library_base.usb.UDiskDevice;
import com.ecarx.module_log.R;
import com.ecarx.module_log.logexport.adapter.UsbDeviceAdapter;

import java.util.List;

public class SpinnerDialog extends Dialog implements View.OnClickListener {
    private static final String TAG = "SpinnerDialog";
    private ClickFinish mClickFinish;
    private TextView mTextName;
    private Spinner mSpinner;

    private TextView mCancelButton;

    private TextView mConfirmButton;

    private String mTextNameString = null;
    private List<UDiskDevice> mDiskDeviceList;
    private Context mContext;
    private UsbDeviceAdapter mUsbDeviceAdapter;

    public SpinnerDialog(@NonNull Context context, String text_nameString, List<UDiskDevice> uDiskDeviceList, ClickFinish clickFinish) {
        super(context, R.style.dialog_pwd);
        this.mTextNameString = text_nameString;
        this.mClickFinish = clickFinish;
        mDiskDeviceList = uDiskDeviceList;
        mContext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = LayoutInflater.from(mContext).inflate(R.layout.spinner_dialog, null);
        setContentView(view);
        initView(view);
        mTextName.setText(mTextNameString);
        initListener();
    }


    private void initListener() {
        mCancelButton.setOnClickListener(this);
        mConfirmButton.setOnClickListener(this);
    }


    private void initView(View view) {
        mTextName = (TextView) view.findViewById(R.id.title);
        mSpinner = (Spinner) view.findViewById(R.id.spinner);
        mCancelButton = (TextView) view.findViewById(R.id.cancel_button);
        mConfirmButton = (TextView) view.findViewById(R.id.confirm_button);
        mUsbDeviceAdapter = new UsbDeviceAdapter(mDiskDeviceList);
        mSpinner.post(() -> mSpinner.setDropDownVerticalOffset(mSpinner.getHeight()));
        mSpinner.setAdapter(mUsbDeviceAdapter);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.confirm_button) {
            UDiskDevice uDiskDevice = (UDiskDevice) mSpinner.getSelectedItem();
            if (mClickFinish != null) {
                mClickFinish.selectFinish(uDiskDevice);
            }
            dismiss();
        } else if (id == R.id.cancel_button) {
            dismiss();
        }
    }

    public void notifyData(List<UDiskDevice> uDiskDevice) {
        if (isShowing() && mUsbDeviceAdapter != null) {
            this.mUsbDeviceAdapter.notifyData(uDiskDevice);
        }
    }

    public interface ClickFinish {
        void selectFinish(UDiskDevice uDiskDevice);
    }
}
